<%@page import="com.sdry.entity.base.Staff"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<jsp:include page="../../common.jsp"></jsp:include>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>待办</title>
<script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath}/statics/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath}/statics/ueditor/ueditor.all.min.js"> </script>
<script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath}/statics/ueditor/lang/zh-cn/zh-cn.js"></script>
<style type="text/css">
	/*初始化编辑器边框*/
	.edui-default .edui-editor {
	    border: 0px solid #d4d4d4;
	}
	/*初始化编辑器高度,默认320*/
	#edui1_iframeholder{
	    height: 60vh !important
	}
</style> 
<%
	Staff staff = (Staff)session.getAttribute("staff");
    Long d = null;
    String name = null;
    String scode = null;
    Long staffId = null;
    String sreserve1 = null;
    System.out.print(staff);
    if(staff != null){
      d = staff.getPid();
      name = staff.getSname();
      scode = staff.getScode();
      staffId = staff.getStaid();
      sreserve1 = staff.getSreserve1();
    }
  %>
<script type="text/javascript">
    //ueditorUE 初始化文本编辑器
    //var ue = UE.getEditor('content');
    var ue = UE.getEditor('html',{
        //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
        toolbars:[],
        //关闭字数统计
        wordCount:false,
        //默认的编辑区域高度
        initialFrameWidth:null,
        //initialFrameHeight:null,  //初始化编辑器高度,默认320
        //更多其他参数，请参考ueditor.config.js中的配置项
    });
    //ueditorUE 去掉本地保存成功的提示框！
    ue.ready(function () {
        $(".edui-editor-messageholder.edui-default").css({ "visibility": "hidden" });
        ue.setDisabled();
    });
</script>
<script type="text/javascript">
$(function () {

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
	//行点击事件
    $('#tb_table').on('click-row.bs.table', function (e, row, element) {initBottomTable(row.approvalid, row.status03);});
    oButtonInit.Init();
	//初始化提示框的位置：top-center，bottom-left，bottom-right
    toastr.options.positionClass = 'toast-top-center';
	
    $('#exampleModal1').on('hide.bs.modal',function(){
    	$("#fm")[0].reset();
    	$('#fm').data('bootstrapValidator').resetForm(true);
    });
	
});

var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#tb_table').bootstrapTable({
            url: "${pageContext.request.contextPath}/approval/findWaitApproved.do",
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: false,                    //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 20, 30],        		//可供选择的每页的行数（*）
            strictSearch: true,
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: false,                //是否启用点击选中行
            height: 550,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "approvalid",             //每一行的唯一标识，一般为主键列
            detailView: false,                  //是否显示父子表
            columns:  [ {
                checkbox: true
            },{
				field : 'approvalid',
				visible : false
			},{
				field : 'applicant',
				align : 'center',
				title : '项目名称',
				formatter: function (value, row, index) {
					var nr = htmlnr(row.approvalid,1);
					if(nr == -1){
						nr = ""
					}
					return nr
				}
			},{
				field : 'applicant',
				align : 'center',
				title : '项目说明',
				formatter: function (value, row, index) {
					var nr = htmlnr(row.approvalid,2);
					if(nr == -1){
						nr = ""
					}
					return nr
				}
			},{
				field : 'applicant',
				align : 'center',
				title : '申请人'
			},{
				field : 'status03',
				align : 'center',
				title : '申请类型'
			}, {
				field : 'remark05',
				align : 'center',
				title : '发起时间'
			}, {
				field : 'status01',
				align : 'center',
				title : '状态',
				formatter: function (value, row, index) {
					var deptLength = row.status02.split(',').length;
					if (row.status02.indexOf('财务部') == -1) {
						return '审批中';
					} else {
						if (deptLength == 2) {
							if (value != 'a1') {
								return '审批中';
							} else {
								return '审批通过';
							}
						}
						if (deptLength == 3) {
							if (value != 'b1') {
								return '审批中';
							} else {
								return '审批通过';
							}
						}
						if (deptLength == 4) {
							if (value != 'c1') {
								return '审批中';
							} else {
								return '审批通过';
							}
						}
					}
                }
			}/* , {
				field : '',
				align : 'center',
				title : '历史批注',
				formatter: function (value, row, index) {
					cell ='<button type="button" class="btn btn-primary" onclick="annotationView('+row.approvalid+')">历史批注</button>';
                    return cell;
				}
			}, {
				field : '',
				align : 'center',
				title : '操作',
				formatter:function(value,row,index){
					if (row.remark04 == '财务部') {
						return '<button type="button" id="btn_preview" class="btn btn-primary" onclick="archive('+row.approvalid+')">结算</button>';
					} else {
						return '<button type="button" id="btn_preview" class="btn btn-primary" onclick="todo('+row.approvalid+')">审批</button>';
					}
	            },
			}, {
				field:'title',
                title:"预览",
                align:'center',
                formatter : function(cell, row, index) {
                	if (row.status03 == '合同协议') {
                		cell ='<button type="button" id="btn_preview" class="btn btn-primary" onclick="displayPreview('+row.approvalid+')">预览</button>';
	                    return cell;
					} else {
						return '';
					}
                }, 
			}  */,{
				field:'title',
                title:"附件预览",
                align:'center',
                visible : false,
                formatter : function(cell, row, index) {
                	if (row.status03 != '合同协议') {
                		var val = row.remark06;
						if (val == '') {
							return '';
						} else {
							//cell ="<button type='button' class='btn btn-primary' onclick='docView(\""+val+"\")'>附件预览</button>";
							cell = "<a href='${pageContext.request.contextPath}/attachment/"+val+"' target='_blank' class='btn btn-primary'>下载</a>"
							return cell;
						}
					} else {
						return '';
					}
                },
			}],
        });
        
      	//合同协议详情
        $('#tb_departmentsDetailed').bootstrapTable({
        	url: "${pageContext.request.contextPath}/agreement/selectAgreementList.do",
            method: 'get',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: false,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParamsDetailed,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 20, 30],        //可供选择的每页的行数（*）
            strictSearch: true,
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "aid",                     //每一行的唯一标识，一般为主键列
            detailView: false,                   //是否显示父子表
            columns: [{
                checkbox: true
            }, {
                field:'aid',
                visible: false,
                title:"编号",
                align:'center'
            },{
                field:'client',
                visible: false,
                title:"类别id",
                align:'center'
            },{
                field:'aremark5',
                title:"类别",
                align:'center'
            },{
                field:'aname',
                title:"标题",
                align:'center'
            },{
                field:'item',
                title:"项目归属",
                align:'center',
   				formatter: function (value, row, index) {
   					var items =value.split(",");
   					if (items.length >= 5) {
   						return items[1];
   					}else{
   						return "";
   					}
   				}
            },{
                field:'item',
                title:"项目名称",
                align:'center',
   				formatter: function (value, row, index) {
   					var items =value.split(",");
   					if (items.length >= 5) {
   						return items[3];
   					}else{
   						return "";
   					}
   				}
            },{
                field:'aid',
                title:"预览",
                align:'center',
                width:"80px",
                formatter : function(cell, row, index) {
                    cell ='<button type="button" id="btn_preview" class="btn btn-primary" onclick="preview('+row.aid+')">预览</button>';
                    return cell;
                },
            },],
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        	offset: params.offset/params.limit+1,   //页面大小
        	limit: params.limit,  //页码
        	applicant:$.trim($('#appc').val()),
        	status03:$.trim($('#status03c').val()),
        };
        return temp;
    };
  	////合同协议详情得到查询的参数
    oTableInit.queryParamsDetailed = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
       		page: params.offset/params.limit+1,   //页面大小
            rows: params.limit,  //页码
            aremark:$.trim($('#id').val()), 
        };
        return temp;
    };
    return oTableInit;
};


var ButtonInit = function () {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        //初始化页面上面的按钮事件
    };

    return oInit;
};

//刷新表格
function seach() {
	$("#tb_table").bootstrapTable("refreshOptions",{pageNumber:1});
}
//批注历史
function annotationView(approvalId) {
	
	var row=$.map($("#tb_table").bootstrapTable('getSelections'),function(row){
		return row ;
	});
	if (row.length == 0) {
		toastr.warning('请至少选择一条数据!');
	}else{
		var approvalId=row[0].approvalid;
		$('#exampleModal2').modal(open);
		$('#annotationInfo').empty();
		jQuery("#annotationInfo").load("${pageContext.request.contextPath}/approval/findAnnotationInfoByID.do?approvalId="+approvalId);
	}
}
//审批
function todo(approvalid) {
	var row=$.map($("#tb_table").bootstrapTable('getSelections'),function(row){
		return row ;
	});
	if(row[0].remark04 == '财务部') {
		toastr.warning('对不起，财务部不能审批，请点击结算按钮!');
		return;
	}
	if (row.length == 0) {
		toastr.warning('请至少选择一条数据!');
	}else{
		$('#approvalid').val(row[0].approvalid);
		$("#bt").html("审批信息");
		addFig  =  false
		$('#exampleModal1').modal(open);
		$("#fm")[0].reset();
	}
}

//结算
function archive(approvalid) {
	var row=$.map($("#tb_table").bootstrapTable('getSelections'),function(row){
		return row ;
	});
	
	if(row[0].remark04 != '财务部') {
		toastr.warning('对不起，财务部才能结算!您没有此权限');
		return;
	}
	
	if (row.length == 0) {
		toastr.warning('请至少选择一条数据!');
	}else{
		$('#approvalid2').val(row[0].approvalid);
		$("#bt2").html("结算信息");
		addFig  =  false
		$('#exampleModal3').modal(open);
		$("#fm2")[0].reset();
	}
}


//保存
addFig  =  false
function save(flag) {

	// 同意：flag == 1  回退：flag== 2
	if(addFig == true){
		return false;
	}
	addFig  =  true;
	$('#type').val(flag)
    var bootstrapValidator = $("#fm").data('bootstrapValidator');  
    //开启验证
    bootstrapValidator.validate();  
    if (bootstrapValidator.isValid()){
		var url = "${pageContext.request.contextPath }/approval/approvalOperate.do";
		//var title="新增";
		$.post(url, $("#fm").serialize(), function(data) {
            if (data == 1) {
            	if (flag == 1) {
            		toastr.success('已同意');
            		
            		var approvalId = $('#approvalid').val();
            		//已同意，根据审批id查询
            		$.ajax({
            	        url: '/approval/selectAgreementByApprovalId.do' ,
            	        type: 'post',
            	        async:false,
            	        dataType:'json',
            	        data:"aremark="+approvalId,
            	        success: function (data) {
            	            if(data != "" || data != undefined || data != null) {
            	            	for(var i = 0;i < data.length; i++) {
            	            		var state = shenpiStare(data[i]);
            	            		if(state == 2) {
            	            			saveBillForm(data[i].aid);
            	            		}
            	            	}
            	            }
            	        }
            	    });
				} else {
					toastr.error('已回退');
				}
            	
            	//根据审批人及审批结果修改呈批件信息
            	updateHtml(flag);
            	
                setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                    $('#exampleModal1').modal('hide');
                    $('#tb_table').bootstrapTable('refresh');
                    //refresh();
                    window.location.reload();
                    addFig  =  false
                },1000);
            } else {
                toastr.error('提交错误，请刷新页面重新提交');
                addFig  =  false
            }
        });
    }else{
	    addFig  =  false
	    return;  
    } 
};



//判断审批状态   0通过  1回退  2通过已结算  -1未审批  -2审批中 
function shenpiStare(row) {
	var stare = -1;
	var value = row.aremark2
	if(value == null || value == ""){
		stare = -1;
	}else{
		var deptLength = row.aremark10.split(",").length;
		if (row.aremark10.indexOf('财务部') != -1) {
			if (deptLength == 2) {
				if (value.indexOf('1') != -1) {
					if (value == 'b1') {
						//return '审批通过(已结算)';
						stare = 2;
					} else {
						//return '审批通过';
						stare = 0;
					} 
				}
			}
			if (deptLength == 3) {
				if (value.indexOf('1') != -1) {
					 if (value == 'c1') {
						//return '审批通过(已结算)';
						 stare = 2;
					} else {
						//return '审批通过';
						stare = 0;
					} 
				}
			}
			if (deptLength == 4) {
				if (value.indexOf('1') != -1) {
					if (value == 'd1') {
						//return '审批通过(已结算)';
						stare = 2;
					} else {
						//return '审批通过';
						stare = 0;
					}
				}
			}
			if (value == '0') {
				//return '审批中';
				stare = -2;
			} 
			if (value.indexOf('2') != -1) {
				//return '已回退';
				stare = 1;
			}
		} else {
			if (deptLength == 1) {
				if (value.indexOf('1') != -1) {
					//return '审批通过(已结算)';
					stare = 2;
				} 
			}
			if (deptLength == 2) {
				if (value.indexOf('1') != -1) {
					if (value == 'b1') {
						//return '审批通过(已结算)';
						stare = 2;
					} else {
						//return '审批中';
						stare = -2;
					}
				}
			}
			if (deptLength == 3) {
				if (value.indexOf('1') != -1) {
					if (value == 'c1') {
						//return '审批通过(已结算)';
						stare = 2;
					} else {
						//return '审批中';
						stare = -2;
					}
				}
			}
			if (deptLength == 4) {
				if (value.indexOf('1') != -1) {
					if (value == 'd1') {
						//return '审批通过(已结算)';
						stare = 2;
					} else {
						//return '审批中';
						stare = -2;
					}
				}
			}
			if (value == '0') {
				//return '审批中';
				stare = -2;
			} 
			if (value.indexOf('2') != -1) {
				//return '已回退';
				stare = 1;
			}
		}
	}
	return stare;
}

//日期拼接时判断是否大于10否则前面加0
function add0(m){
	if(m.length > 1){
		return m;
	}else{
		var m1= Number(m);
		return m1<10?'0'+m1:m1; 
	}
}
//根据文档id获取文档内容
function getHtml(aid) {
var html = "";
$.ajax({
	url: '/agreement/selectAgreementById.do' ,
	type: 'post',
	async:false,
	dataType:'json',
	data:"id="+aid,
	success: function (data) {
		html = data.html;
	},
});
return html;
}
//根据文档id提取文档信息保存至表单
function saveBillForm(aid) {
   	var billFormName = "";
   	var billFormType = "";
   	var data = getHtml(aid);
   	var arr = data.split("汇款领用单");
   	var num = 0;
   	if(arr.length > 1 ){
   		var arr1 = arr[1].split("</span>");
   		billFormType = "汇款领用单"+arr1[0];
   		if(billFormType != "汇款领用单（机关）"){
    		billFormName = tableHtmlnr(data,"table",1);
    		num = 1;
   		}
   	}else{
   		var zarr = data.split("支票领用单");
   		var zarr1 = zarr[1].split("</span>");
   		billFormType = "支票领用单"+zarr1[0];
   		
   	}
   	var year = tableHtmlnr(data,"table",num+1);
   	var month = tableHtmlnr(data,"table",num+2);
   	var day = tableHtmlnr(data,"table",num+3);
    var billFormTime=year+"-"+add0(month)+"-"+add0(day);
    var bfremark=tableHtmlnr(data,"table",num+4);
    var billFormItem=tableHtmlnr(data,"table",num+5);
    var billFormMoney=tableHtmlnr(data,"table",num+6);
   	$.ajax({
           url: "${pageContext.request.contextPath}/billForm/insertbillForm.do",
           type: 'post',
           data:{"aid":aid,"billFormName":billFormName
           	,"billFormType":billFormType
           	,"billFormTime":billFormTime
           	,"bfremark":bfremark
           	,"billFormItem":billFormItem
           	,"billFormMoney":billFormMoney},
           async:false,
           dataType:'json',
           success: function (data1) {
               if (data1 == 1) {
				   toastr.success('表单统计成功')
               } else {
               		toastr.error('表单统计失败')
               }
           },
       });
}


	//把审批内容添加入呈批件内容（替换表格里第一个*）中
function tableHtmlnr(data,s,num) {
    //返回数据
    var html = "";
    //标签头
    var tableq = "<"+s
	//标签尾
    var tableh = "</"+s+">"
    //标签头分组
    var strks = data.split(tableq);
    //标签尾分组
    var strjs = data.split(tableh);

    for (var i=0;i<strks.length;i++) {
        if(i == 0){
            
        }else {
        	//获取相同值（table内容）
            var ss = getMaxStr(strks[i], strjs[i-1].split(tableq)[1])
            var qh = ss.split("{[");
            var hh = ss.split("]}");
            //第num个{[]}的内容
            html = getMaxStr(qh[num], hh[num-1].split("{[")[1])
            if(html == -1){
            	html = ""
            }
        }
    }
    return html;
}


//获取俩字符中相同字段
function getMaxStr(str1,str2){
    var max = str1.length > str2.length ? str1 : str2;
    var min = (max == str1 ? str2 : str1);
    for(var i = 0; i < min.length; i++){
        for(var x = 0, y = min.length - i;y != min.length + 1;x++,y++){
            //y表示所取字符串的长度
            var newStr = min.substring(x,y);
            //判断max中是否包含newStr
            if(max.indexOf(newStr) != -1){
                return newStr;
            }
        }
    }
    return -1;
}


//获取当前时间
function CurentTime() {
	 
	var now=new Date();
	var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日
 	var hours = now.getHours(); //获取当前小时数(0-23)
  	var minutes = now.getMinutes(); //获取当前分钟数(0-59)
  	var seconds = now.getSeconds(); //获取当前秒数(0-59)
    //var mill=now.getMilliseconds();
    var time=year+"-"+add0(month)+"-"+add0(day)+" "+add0(hours)+":"+add0(minutes)+":"+add0(seconds);
	 
	 return time;
}
function add0(m){return m<10?'0'+m:m }
//根据审批人及审批结果修改呈批件信息
function updateHtml(flag) {
	var approvalId = $('#approvalid').val();
	var msg = $('#msg').val();
	var date = CurentTime();
	// 同意：flag == 1  回退：flag== 2
	var name = '<%=name%>'
	if(flag == 1){
		name = "同意审批"
				+"     "+"审批意见："+msg
				+"     "+"审批人："+name+""
				+"     "+"审批时间："+date+""
	}else if(flag == 0){
		name = "回退审批"
			+"     "+"审批意见："+msg
			+"     "+"审批人："+name+""
			+"     "+"审批时间："+date+""
	}
	var sreserve1 = '<%=sreserve1%>';
	console.log(sreserve1)
	//sreserve1 = $.trim(sreserve1);
	
	console.log(sreserve1)
	if(sreserve1 != "" && sreserve1 != undefined && sreserve1 != 'null'  && sreserve1 != null){
		console.log(sreserve1+"dd")
		name = name + "<img src = '${pageContext.request.contextPath}/"+sreserve1+"' style=\"height: 100%;width: 40%;\"/>"
	}
	
	$.ajax({
        url: '/agreement/selectAgreementByExample.do' ,
        type: 'post',
        async:false,
        dataType:'json',
        data:"aremark="+approvalId,
        success: function (data) {
            if(data.length > 1){
                for(var i = 0; i < data.length; i++){
	                if(data[i].aremark5 == "呈批件"){
	                	var html = tableGl(data[i].html,"table",name);
	                	updateCPJ(html,data[i].aid)
		                break;
	                }
                }
            }
        },
    });
}
//根据id提交修改内容
function updateCPJ(html,aid) {
    $.ajax({
        url: "${pageContext.request.contextPath}/agreement/editHtml.do" ,
        type: 'post',
        data:{"aid":aid,"html":html},
        async:false,
        success: function (data1) {
            if (data1 == 1) {
            	 //toastr.success('成功')
            } else {
            	//toastr.error('失败')
            }
        },
    });
}
//把审批内容添加入呈批件内容（替换表格里第一个*）中
function tableGl(data,s,str) {
    //返回数据
    var dept = "*";
    var html = "";
    //标签头
    var tableq = "<"+s
	//标签尾
    var tableh = "</"+s+">"
    //标签头分组
    var strks = data.split(tableq);
    //标签尾分组
    var strjs = data.split(tableh);

    for (var i=0;i<strks.length;i++) {
        if(i == 0){
            html = html + strks[i];
        }else {
        	//获取相同值（table内容）
            var ss = getMaxStr(strks[i], strjs[i-1].split(tableq)[1])
            var qianHou = strks[i].split(ss);
			var darr = ss.split(dept)
			//头：darr[0]
			//中间行：darr[1] == darr[N-1]
			//尾：darr[N]
			var zjh = darr[1];
            if (darr.length == 2) {
				ss = darr[0] + str +darr[1];
			}else if(darr.length >= 3){
				ss = darr[0] + str + darr[1]
				for(var i = 2;i<darr.length;i++) {
					ss = ss + dept + darr[i] 
            	}
			}
			html = html + tableq + qianHou[0]+ss+ tableh+ qianHou[1];
        }
    }
    return html;
}

//获取俩字符中相同字段
function getMaxStr(str1,str2){
    var max = str1.length > str2.length ? str1 : str2;
    var min = (max == str1 ? str2 : str1);
    for(var i = 0; i < min.length; i++){
        for(var x = 0, y = min.length - i;y != min.length + 1;x++,y++){
            //y表示所取字符串的长度
            var newStr = min.substring(x,y);
            //判断max中是否包含newStr
            if(max.indexOf(newStr) != -1){
                return newStr;
            }
        }
    }
    return -1;
}


//结算保存
addFig  =  false
function save2() {

	// 同意：flag == 1  回退：flag== 2
	if(addFig == true){
		return false;
	}
	addFig  =  true;
    var bootstrapValidator = $("#fm2").data('bootstrapValidator');  
    //开启验证
    bootstrapValidator.validate();  
    if (bootstrapValidator.isValid()){
		var url = "${pageContext.request.contextPath }/approval/approvalOperate.do";
		//var title="新增";
		$.post(url, $("#fm2").serialize(), function(data) {
            if (data == 1) {
            	toastr.success('已结算');
            	var approvalId = $('#approvalid2').val();
        		//已同意，根据审批id查询
        		$.ajax({
        	        url: '/approval/selectAgreementByApprovalId.do' ,
        	        type: 'post',
        	        async:false,
        	        dataType:'json',
        	        data:"aremark="+approvalId,
        	        success: function (data) {
        	            
        	        	if(data != "" || data != undefined || data != null) {
        	            	for(var i = 0;i < data.length; i++) {
        	            		var state = shenpiStare(data[i]);
        	            		if(state == 2) {
        	            			saveBillForm(data[i].aid);
        	            		}
        	            	}
        	            }
        	        }
        	    });
                setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                    $('#exampleModal3').modal('hide');
                    $('#tb_table').bootstrapTable('refresh');
                    //refresh();
                    addFig  =  false
                },1000);
            } else {
                toastr.error('提交错误，请刷新页面重新提交');
                addFig  =  false
            }
        });
    }else{
	    addFig  =  false
	    return;  
    } 
};

//预览
function htmlnr(approvalId,num){
	var nr = "";
	$.ajax({
        url: '/agreement/selectAgreementByExample.do' ,
        type: 'post',
        async:false,
        dataType:'json',
        data:"aremark="+approvalId,
        success: function (data) {
            if(data.length > 1){
                for(var i = 0; i < data.length; i++){
	                if(data[i].aremark5 == "呈批件"){
	                	nr = tableHtmlnr(data[i].html,"table",num);
		                break;
	                }
                }
            }
        },
    });
	return nr;
}

//把审批内容添加入呈批件内容（替换表格里第一个*）中
function tableHtmlnr(data,s,num) {
    //返回数据
    var dept = "*";
    var html = "";
    //标签头
    var tableq = "<"+s
	//标签尾
    var tableh = "</"+s+">"
    //标签头分组
    var strks = data.split(tableq);
    //标签尾分组
    var strjs = data.split(tableh);

    for (var i=0;i<strks.length;i++) {
        if(i == 0){
            
        }else {
        	//获取相同值（table内容）
            var ss = getMaxStr(strks[i], strjs[i-1].split(tableq)[1])
            var qh = ss.split("{[");
            var hh = ss.split("]}");
            //第num个{[]}的内容
            var html = getMaxStr(qh[num], hh[num-1].split("{[")[1])
        }
    }
    return html;
}
function displayPreview(approvalId){
	//alert(approvalId)
	/* $.ajax({
        url: '${pageContext.request.contextPath}/approval/queryHTMLByAppId.do' ,
        //dataType: 'json',
        type: 'post',
        data:{"approvalId":approvalId},
        success: function (data) {
        	var jsonObj = eval('(' + data + ')');
        	console.log(jsonObj.html);
            if(jsonObj.html == null){
                toastr.warning('该内容为空');
            }else{
                ue.setContent(jsonObj.html);
                $('#exampleModal').modal(open);
            }
        },
        error: function (data){
        	alert(jsonObj.html)
        }
    }); */
    
    var row=$.map($("#tb_table").bootstrapTable('getSelections'),function(row){
		return row ;
	});
	if (row.length == 0) {
		toastr.warning('请至少选择一条数据!');
	}else{
		var approvalId = row[0].approvalid; 
		$.ajax({
	        url: '/agreement/selectAgreementByExample.do' ,
	        type: 'post',
	        async:false,
	        dataType:'json',
	        data:"aremark="+approvalId,
	        success: function (data) {
	            if(data.length <= 0){
	                toastr.warning('该内容为空');
	            }else if(data.length == 1){
	                ue.setContent(data[0].html);
	                $('#exampleModal').modal(open);
	            }else{
	                for(var i = 0; i < data.length; i++){
		                if(data[i].aremark5 == "呈批件"){
		                	ue.setContent(data[i].html);
			                $('#exampleModal').modal(open);
			                break;
		                }
	                }
	            }
	        },
	    });
	}
}

//合同协议详情内容预览
function preview(tid) {
    $.ajax({
        url: '/agreement/selectAgreementById.do' ,
        type: 'post',
        async:false,
        dataType:'json',
        data:"id="+tid,
        success: function (data) {
            if(data.html == null){
                toastr.warning('该内容为空');
            }else{
                ue.setContent(data.html);
                $('#exampleModal').modal(open);
            }
        },
    });
}

//附件预览
function docView(docPath){
	$.ajax({
        url: '${pageContext.request.contextPath}/approval/docToHtml.do' ,
        type: 'post',
        async: false,
        data:{"docPath":docPath},
        success: function (realPath) {
        	//alert("${pageContext.request.contextPath}/attachment/" + realPath.trim());
        	window.open("${pageContext.request.contextPath}/attachment/" + realPath.trim());
        }
    });
}

//修改附件
function doUpdate() {
	var row = $.map($("#tb_table").bootstrapTable('getSelections'),function(row){
		return row ;
	});
	if (row.length == 0) {
		toastr.warning('请至少选择一条数据!');
	} else if (row.length == 1) {
		if ('合同协议' == row[0].status03) {
			toastr.warning('合同协议无附件，请重新选择数据!');
		} else if (row[0].remark06 == '') {
			toastr.warning('未上传附件，请重新选择数据!');
		} else {
			$('#approvalId').val(row[0].approvalid);
			$('#attachmentUpdate').modal(open);
			$('#updateApproval').on('click', function() {
				var attachment = $('#attachment').val();
				if (attachment == '') {
					toastr.warning('请选择附件！');
					return false;
				}
				var form = new FormData(document.getElementById("updateForm"));
				$.ajax({
					type : "post",
					url : "${pageContext.request.contextPath}/initiateMana/updateApproval.do",
					data : form,
					processData:false,
		            contentType:false,
					success : function(data) {
						if(data) {
							toastr.success('附件保存成功！');
							$("#clean").click();
							setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
								//关闭模态框
								// 父页面刷新
								window.location.reload();  
							},2000);
						} else {
							toastr.warning('附件保存出现错误！');
						}
					},
					error : function () {
						toastr.error('附件保存失败！');
					}
				});
			})
		}
	} else {
		toastr.warning('每次只能选择一条数据!');
	}
}
</script>
</head>
<body>
	<div class="panel-body" style="padding-bottom:0px;">
        <div class="panel panel-default">
            <div class="panel-body" style="padding: 5px;">
                <form id="formSearch" class="form-horizontal">
                    <div class="form-group" style="margin-top:15px;margin: 0px;">
                        <label class="control-label col-sm-1" for="preHtmlTJ">申请类型</label>
                        <div class="col-sm-2">
                            <input type="text" class="form-control" id="status03c">
                        </div>
						<label class="control-label col-sm-1" for="titleTJ">申请人</label>
                        <div class="col-sm-2">
                            <input type="text" class="form-control" id="appc">
                        </div>
                        <div class="col-sm-4">
                            <button type="button" style="margin-left: 5%;" id="btn_query" class="btn btn-primary" onclick="seach()">查询</button>
                        	&nbsp;&nbsp;
                        	<button id="btn_add" type="button" class="btn btn-primary"  onclick="annotationView()">历史批注</button>
                        	&nbsp;&nbsp;
                        	<button id="btn_add" type="button" class="btn btn-primary"  onclick="todo()">审批</button>
                        	&nbsp;&nbsp;
                        	<button id="btn_add" type="button" class="btn btn-primary"  onclick="archive()">结算</button>
                        	&nbsp;&nbsp;
                        	<button id="btn_add" type="button" class="btn btn-primary"  onclick="displayPreview()">预览</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <table id="tb_table"></table>
        <!--    底部详情表格   -->
        <div id="detail" class="bootstrap-table">
        	<div class="fixed-table-container">
        		<div  style="display:none;" id="xmDiv">
        			<input type="hidden" id="id" value="0">
        			<table id="tb_departmentsDetailed"></table>
        		</div>
        		<div id="fXmDiv">
	        		<div class="fixed-table-header">
	        			<table class="table table-hover table-striped">
			        		<thead>
			        			<tr id="thead_tr1">
			        			</tr>
			        		</thead>
			        	</table>
	        		</div>
	        		<div class="fixed-table-body">
	        			<table class="table table-hover table-striped" style="margin-top: -40px;">
			        		<thead>
			        			<tr id="thead_tr2">
			        			</tr>
			        		</thead>
			        		<tbody>
			        			<tr id="tbody_tr">
			        			</tr>
			        		</tbody>
			        	</table>
	        		</div>
        		</div>
        		
        	</div>
        </div>
    </div>
    <div class="modal fade" id="exampleModal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content" style="width: 700px;">
      			<div class="modal-header">
        			<button type="button" class="close closefm" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title" id="exampleModalLabel">
        				<span id="bt" style="font-size:13px"></span>
        			</h4>
      			</div>
      			<div class="modal-body">
	        		<form id="fm" class="form-horizontal">
	          			<div class="form-group">
	           				 <label class="col-sm-3 control-label">审批意见:</label>
	            			 <div class="col-sm-7"> 
								<input type="text" class="form-control" id="msg" name="msg"  placeholder="请输入审批意见" autocomplete="off">
		            			 <input type="hidden" id="approvalid" name="approvalid" >
		            			 <input type="hidden" id="type" name="type" >
	          				</div>
	          			</div>
	          			 <div class="modal-footer">
					        <button type="button"  class="btn btn-primary" onclick="save(1)">同意</button>
					        <button type="button"  class="btn btn-primary" onclick="save(2)">回退</button>
                          	<button type="button" class="btn btn-default closefm" data-dismiss="modal" >关闭</button>
                        </div>
	        		</form>
	      		</div>
    		</div>
  		</div>
	</div>
	<!-- 批注信息  -->
	<div class="modal fade" id="exampleModal2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content" style="width: 700px;">
      			<div class="modal-header">
        			<button type="button" class="close closefm" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title" id="exampleModalLabel">
        				<span id="bt" style="font-size:13px">历史批注</span>
        			</h4>
      			</div>
      			<div class="modal-body" id="annotationInfo" style="height: 400px;">
	      		</div>
    		</div>
  		</div>
	</div>
    <div class="modal fade" id="exampleModal3" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content" style="width: 700px;">
      			<div class="modal-header">
        			<button type="button" class="close closefm" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title" id="exampleModalLabel">
        				<span id="bt2" style="font-size:13px"></span>
        			</h4>
      			</div>
      			<div class="modal-body">
	        		<form id="fm2" class="form-horizontal">
	          			<div class="form-group">
	           				 <label class="col-sm-3 control-label">结算批注:</label>
	            			 <div class="col-sm-7"> 
								<input type="text" class="form-control" id="msg2" name="msg"  placeholder="请输入结算批注" autocomplete="off">
		            			 <input type="hidden" id="approvalid2" name="approvalid" >
	          				</div>
	          			</div>
	          			 <div class="modal-footer">
					        <button type="button"  class="btn btn-primary" onclick="save2()">结算</button>
                          	<button type="button" class="btn btn-default closefm" data-dismiss="modal" >关闭</button>
                        </div>
	        		</form>
	      		</div>
    		</div>
  		</div>
	</div>
	<div class="modal fade bs-example-modal-lg" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    	<div class="modal-dialog modal-lg" role="document">
        	<div class="modal-content">
	            <div class="modal-header">
	                <button type="button" class="close closefm" data-dismiss="modal" aria-label="Close">
	                    <span aria-hidden="true">&times;</span>
	                </button>
	                <h4 class="modal-title" id="exampleModalLabel">
	                    <span style="font-size:13px">预览</span>
	                &nbsp;&nbsp;&nbsp;&nbsp;
	                <button type="button" class="btn btn-default" onclick="dy()">
	                    <span class="glyphicon glyphicon-print" aria-hidden="true"></span>
	                </button>
	                </h4>
	                <script type="text/javascript">
                    function dy() {
                    	var css="<style>"
                            +"table {border-collapse: collapse;" +
                                "border:1px #ddd solid;" +
                           "}"
                           +"table tr td {" +
                                "border:1px #ddd solid;" +
                           "}"
                            +"</style>";
                        var printHtml = css + ue.getContent();
                    	printpage(printHtml)
                    }
                   
                    function printpage(printHtml){    
                    	var wind = window.open("",'newwindow', 'top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no');
                    	wind.document.body.innerHTML = printHtml;
                    	wind.print();
                    	return false; 
                    }
                </script>
	            </div>
	            <div class="modal-body" >
	                <textarea id="html" name="html"></textarea>
	            </div>
        	</div>
    	</div>
	</div>
	
	<!-- 附件修改  -->
	<div class="modal fade" id="attachmentUpdate" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content" style="width: 700px;">
      			<div class="modal-header">
        			<button type="button" class="close closefm" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title">
        				<span id="bt" style="font-size:13px">附件修改</span>
        			</h4>
      			</div>
      			<div class="modal-body">
      				<form id="updateForm" class="form-horizontal">
      					<input type="hidden" id="approvalId" name="approvalId">
	          			<div class="form-group">
	           				 <label class="col-sm-3 control-label">附件:</label>
	            			 <div class="col-sm-7"> 
		            			 <input type="file" id="attachment" name="attachment" accept=".doc,.docx">
	          				</div>
	          			</div>
	          			<div style="text-align: center;width: 100%;">
							<button type="button" class="btn btn-primary" id="updateApproval">保存</button>&nbsp;&nbsp;&nbsp;&nbsp;
							<button type="button" class="btn btn-default closefm" data-dismiss="modal" >关闭</button>
						</div>
      				</form>
	      		</div>
    		</div>
  		</div>
	</div>
</body>
<script>
	//底部详情列表初始化
	function initBottomTable(approvalId, status03){
		/* if ('合同协议' != status03) {
			$.ajax({
	            type: "post",
	            url: "${pageContext.request.contextPath}/initiateMana/findDetailByID.do?approvalId="+approvalId,
	            dataType: "json",
	            success: function(data){
	            	console.log(data)
	            	$('#thead_tr1').empty();
					$('#thead_tr2').empty();
					$('#tbody_tr').empty();
	            	var fields = data.mFields.split(',');
					var values = data.mValues.split(',');
					var theadHtml = '';
					var tbodyHtml = '';
					for (var i = 0; i < fields.length; i++) {
						theadHtml = theadHtml + '<th style="text-align: center; " data-field="applicant"><div class="th-inner ">'+
							fields[i] + '</div><div class="fht-cell" style="width: 151px;"></div></th>';
						tbodyHtml = tbodyHtml + '<td style="text-align: center;width: ' + (100/fields.length) + '%;">' + values[i] + '</td>';
					}
					$('#thead_tr1').append(theadHtml);
					$('#thead_tr2').append(theadHtml);
					$('#tbody_tr').append(tbodyHtml);
	            }
	        });
			 $("#fXmDiv").show();
			 $("#xmDiv").hide();
			
		}else{ */
	    	$("#id").val(approvalId);
	        $('#tb_departmentsDetailed').bootstrapTable('refresh');
	        $("#xmDiv").show();
			$("#fXmDiv").hide();
		/* } */
	}
</script>
	<script type="text/javascript">
		$(function() {
			$("#fm").bootstrapValidator({
				feedbackIcons : {
					valid : 'glyphicon glyphicon-ok',
					invalid : 'glyphicon glyphicon-remove',
					validating : 'glyphicon glyphicon-refresh'
				},
				fields : {
					msg : {
						validators : {
							notEmpty : {
								message : '审批意见不能为空'
							},
						}
					},
				},
			});
		});
		$(function() {
			$("#fm2").bootstrapValidator({
				feedbackIcons : {
					valid : 'glyphicon glyphicon-ok',
					invalid : 'glyphicon glyphicon-remove',
					validating : 'glyphicon glyphicon-refresh'
				},
				fields : {
					msg : {
						validators : {
							notEmpty : {
								message : '结算批注不能为空'
							},
						}
					},
				},
			});
		});
	</script>
</html>
